import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Tag, message, Modal, Form, Input, Select, InputNumber, Switch, Row, Col, Upload, Popconfirm, List, Tooltip } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, ShoppingCartOutlined, SearchOutlined, ReloadOutlined, SettingOutlined, PictureOutlined, UploadOutlined, CloseOutlined, StarOutlined, StarFilled, UpOutlined, DownOutlined, ReloadOutlined as ResetOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import SearchForm, { SearchFieldConfig } from '@/components/SearchForm';
import DataTable, { PaginationConfig, ToolbarAction, BatchAction } from '@/components/DataTable';
import {
  getProductList,
  createProduct,
  updateProduct,
  deleteProduct,
  uploadProductImages,
  uploadProductDetailImage,
  deleteProductImage,
  createConfig,
  updateConfig,
  getConfigList,
  getProductFeatures,
  updateProductFeatures,
  addProductFeature,
  deleteProductFeature,
  resetProductFeatures,
  type Product,
  type ProductQueryParams,
  type CreateProductRequest,
  type UpdateProductRequest,
  type CreateConfigRequest,
  type ProductFeature,
  type CreateFeatureRequest
} from '@/services/products';
import {
  getCategoryTree,
  type Category
} from '@/services/categories';

const { Option } = Select;
const { Dragger } = Upload;

// 产品规格字段接口
interface ConfigField {
  key: string;
  field: string;
  description: string;
}

// 产品规格模态框组件
const ProductConfigModal: React.FC<{
  visible: boolean;
  product: Product | null;
  onCancel: () => void;
  onOk: (productId: number, config: Record<string, any>, isEdit: boolean) => void;
}> = ({ visible, product, onCancel, onOk }) => {
  const [configFields, setConfigFields] = useState<ConfigField[]>([
    { key: '1', field: '', description: '' }
  ]);
  const [loading, setLoading] = useState(false);
  const [loadingConfig, setLoadingConfig] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [configForm] = Form.useForm(); // 用于名称和描述

  const addField = () => {
    const newKey = Date.now().toString();
    setConfigFields([...configFields, { key: newKey, field: '', description: '' }]);
  };

  const removeField = (key: string) => {
    if (configFields.length === 1) {
      message.warning('至少需要一个规格字段');
      return;
    }
    setConfigFields(configFields.filter(item => item.key !== key));
  };

  const updateField = (key: string, type: 'field' | 'description', value: string) => {
    setConfigFields(configFields.map(item =>
      item.key === key ? { ...item, [type]: value } : item
    ));
  };

  const handleOk = async () => {
    try {
      // 验证表格字段
      const emptyFields = configFields.filter(item => !item.field.trim() || !item.description.trim());
      if (emptyFields.length > 0) {
        message.error('请填写所有字段和描述');
        return;
      }

      // 检查字段重复
      const fieldNames = configFields.map(item => item.field.trim());
      const uniqueFields = new Set(fieldNames);
      if (fieldNames.length !== uniqueFields.size) {
        message.error('字段名称不能重复');
        return;
      }

      // 验证表单字段
      const formValues = await configForm.validateFields();

      // 转换表格为JSON格式
      const components: Record<string, any> = {};
      configFields.forEach(item => {
        components[item.field.trim()] = item.description.trim();
      });

      // 组合完整的配置数据
      const configData = {
        ...formValues,
        components
      };

      setLoading(true);
      await onOk(product!.id, configData, isEditMode);
    } catch (error) {
      console.error('保存失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const resetFields = () => {
    setConfigFields([{ key: '1', field: '', description: '' }]);
    configForm.resetFields();
    setIsEditMode(false);
  };

  // 加载现有配置数据
  const loadExistingConfig = async (productId: number) => {
    try {
      setLoadingConfig(true);
      // 通过产品名称查找对应的配置
      const response = await getConfigList({ keyword: product?.name, limit: 1 });

      if (response.success && response.data.items && response.data.items.length > 0) {
        const config = response.data.items[0];

        // 设置表单基本信息
        configForm.setFieldsValue({
          name: config.name,
          description: config.description,
          category: config.category,
          total_price: typeof config.total_price === 'number' ? config.total_price : parseFloat(config.total_price) || 0,
          performance_score: typeof config.performance_score === 'number' ? config.performance_score : parseFloat(config.performance_score) || 0,
          image_url: config.image_url,
        });

        // 设置表格字段
        if (config.components) {
          const fields: ConfigField[] = Object.entries(config.components).map(([field, description], index) => ({
            key: `existing_${index}`,
            field,
            description: String(description)
          }));

          if (fields.length > 0) {
            setConfigFields(fields);
          }
        }

        setIsEditMode(true);
      } else {
        // 没有找到现有配置，设置默认值
        configForm.setFieldsValue({
          name: `${product?.name} 规格`,
          description: `${product?.name} 的自定义规格配置`,
          category: 'custom',
          total_price: 0,
          performance_score: 60,
          image_url: '',
        });
        setConfigFields([{ key: '1', field: '', description: '' }]);
        setIsEditMode(false);
      }
    } catch (error) {
      console.log('获取规格失败，将创建新规格:', error);
      resetFields();
    } finally {
      setLoadingConfig(false);
    }
  };

  // 快速添加常用规格字段
  const addCommonField = (field: string, description: string) => {
    const newKey = Date.now().toString();
    setConfigFields([...configFields, { key: newKey, field, description }]);
  };

  // 常用规格字段模板
  const commonFields = [
    { field: 'CPU', description: '处理器型号' },
    { field: 'GPU', description: '显卡型号' },
    { field: 'RAM', description: '内存容量' },
    { field: 'Storage', description: '存储容量' },
    { field: 'Display', description: '显示器规格' },
    { field: 'OS', description: '操作系统' },
  ];

  // 当模态框打开时加载现有配置
  useEffect(() => {
    if (visible && product) {
      loadExistingConfig(product.id);
    } else if (!visible) {
      resetFields();
    }
  }, [visible, product]);

  return (
    <Modal
      title={
        <div className="flex items-center">
          <SettingOutlined className="mr-2" />
          为产品 "{product?.name}" 添加规格
        </div>
      }
      open={visible}
      onOk={handleOk}
      onCancel={onCancel}
      width={800}
      maskClosable={false}
      confirmLoading={loading}
      okText={isEditMode ? "更新规格" : "保存规格"}
      cancelText="取消"
    >
      <div className="mb-4">
        <div className={`mb-4 p-3 border rounded ${isEditMode ? 'bg-orange-50 border-orange-200' : 'bg-blue-50 border-blue-200'}`}>
          <div className={`text-sm mb-2 ${isEditMode ? 'text-orange-700' : 'text-blue-700'}`}>
            <strong>{isEditMode ? '编辑模式：' : '新建模式：'}</strong>
            {isEditMode
              ? '当前显示的是该产品的现有规格，您可以修改后保存。'
              : '您可以通过表格形式添加产品规格字段，系统会自动将其转换为JSON格式保存。'
            }
          </div>
          <div className={`text-xs ${isEditMode ? 'text-orange-600' : 'text-blue-600'}`}>
            {isEditMode
              ? `正在编辑产品ID ${product?.id} 的现有规格`
              : `规格将保存为：产品ID ${product?.id} 的自定义规格`
            }
          </div>
        </div>

        {/* 基本信息表单 */}
        <Form form={configForm} layout="vertical" className="mb-6">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="规格名称"
                rules={[{ required: true, message: '请输入规格名称' }]}
              >
                <Input placeholder={`${product?.name} 规格`} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="category"
                label="类别"
                rules={[{ required: true, message: '请选择类别' }]}
              >
                <Select placeholder="请选择类别">
                  <Option value="gaming">游戏配置</Option>
                  <Option value="office">办公配置</Option>
                  <Option value="design">设计配置</Option>
                  <Option value="server">服务器配置</Option>
                  <Option value="custom">自定义配置</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="description"
            label="规格描述"
            rules={[{ required: true, message: '请输入规格描述' }]}
          >
            <Input.TextArea placeholder="请描述这个规格的特点和用途" rows={2} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={8}>
              <Form.Item
                name="total_price"
                label="总价格"
                rules={[
                  { required: true, message: '请输入总价格' },
                  { type: 'number', min: 0.01, message: '总价格必须大于0' }
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入总价格"
                  min={0}
                  precision={2}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value!.replace(/¥\s?|(,*)/g, '') as any}
                />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="performance_score"
                label="性能评分"
                rules={[
                  { required: true, message: '请输入性能评分' },
                  { type: 'number', min: 0, max: 100, message: '性能评分必须在0-100之间' }
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入性能评分"
                  min={0}
                  max={100}
                />
              </Form.Item>
            </Col>

          </Row>
        </Form>

        {loadingConfig && (
          <div className="text-center py-4">
            <span className="text-gray-500">正在加载现有规格...</span>
          </div>
        )}

        <div className="flex justify-between items-center mb-3">
          <span className="font-medium">规格字段</span>
          <div className="flex gap-2">
            <Button type="primary" size="small" onClick={addField}>
              添加字段
            </Button>
            <Button
              size="small"
              onClick={() => {
                Modal.info({
                  title: '常用规格模板',
                  content: (
                    <div>
                      <p className="mb-3">点击下面的按钮可快速添加常用规格字段：</p>
                      <div className="flex flex-wrap gap-2">
                        {commonFields.map((item) => (
                          <Button
                            key={item.field}
                            size="small"
                            onClick={() => {
                              addCommonField(item.field, item.description);
                              Modal.destroyAll();
                            }}
                          >
                            {item.field}: {item.description}
                          </Button>
                        ))}
                      </div>
                    </div>
                  ),
                  width: 500,
                });
              }}
            >
              快速模板
            </Button>
          </div>
        </div>

        <div className="space-y-3 max-h-64 overflow-y-auto">
          {configFields.map((item, index) => (
            <div key={item.key} className="flex gap-3 items-center p-2 border rounded hover:bg-gray-50">
              <div className="w-8 text-center text-xs text-gray-500">
                {index + 1}
              </div>
              <div className="flex-1">
                <Input
                  placeholder="字段名称 (如: CPU)"
                  value={item.field}
                  onChange={(e) => updateField(item.key, 'field', e.target.value)}
                />
              </div>
              <div className="flex-1">
                <Input
                  placeholder="字段描述 (如: Intel Core i7-12700K)"
                  value={item.description}
                  onChange={(e) => updateField(item.key, 'description', e.target.value)}
                />
              </div>
              <Button
                type="link"
                danger
                size="small"
                onClick={() => removeField(item.key)}
                disabled={configFields.length === 1}
                title={configFields.length === 1 ? '至少需要一个字段' : '删除此字段'}
              >
                删除
              </Button>
            </div>
          ))}
        </div>


      </div>
    </Modal>
  );
};

// 商品图片上传模态框组件
const ProductImagesModal: React.FC<{
  visible: boolean;
  product: Product | null;
  onCancel: () => void;
  onOk: () => void;
}> = ({ visible, product, onCancel, onOk }) => {
  const [fileList, setFileList] = useState<any[]>([]);
  const [detailFileList, setDetailFileList] = useState<any[]>([]);
  const [uploading, setUploading] = useState(false);
  const [existingImages, setExistingImages] = useState<string[]>(['', '', '', '', '']); // 固定5位数组

  // 加载现有图片
  const loadExistingImages = () => {
    if (product?.images) {
      try {
        const images = typeof product.images === 'string' ? JSON.parse(product.images) : product.images;
        if (Array.isArray(images)) {
          // 确保数组长度为5，空位置填充空字符串
          const fullImages = [...images];
          while (fullImages.length < 5) {
            fullImages.push('');
          }
          setExistingImages(fullImages.slice(0, 5)); // 只取前5位
        } else {
          setExistingImages(['', '', '', '', '']);
        }
      } catch (e) {
        setExistingImages(['', '', '', '', '']);
      }
    } else {
      setExistingImages(['', '', '', '', '']);
    }
  };

  // 获取普通图片（前4张）
  const getNormalImages = () => existingImages.slice(0, 4).filter(img => img !== '');

  // 获取详情图（第5张）
  const getDetailImage = () => existingImages[4] || '';

  // 处理普通图片上传
  const handleUpload = async () => {
    const normalImages = getNormalImages();
    const newCount = fileList.length;

    if (newCount === 0) {
      message.warning('请选择要上传的图片');
      return;
    }

    if (normalImages.length + newCount > 4) {
      message.error(`当前已有${normalImages.length}张普通图片，最多只能再上传${4 - normalImages.length}张`);
      return;
    }

    try {
      setUploading(true);
      const files = fileList.map(file => file.originFileObj);
      await uploadProductImages(product!.id, files);
      message.success('图片上传成功');
      setFileList([]);
      loadExistingImages(); // 重新加载图片
      onOk();
    } catch (error) {
      console.error('图片上传失败:', error);
      message.error('图片上传失败');
    } finally {
      setUploading(false);
    }
  };

  // 处理详情图上传
  const handleDetailUpload = async () => {
    if (detailFileList.length === 0) {
      message.warning('请选择要上传的详情图');
      return;
    }

    try {
      setUploading(true);
      const file = detailFileList[0].originFileObj;
      await uploadProductDetailImage(product!.id, file);
      message.success('详情图上传成功');
      setDetailFileList([]);
      loadExistingImages(); // 重新加载图片
      onOk();
    } catch (error) {
      console.error('详情图上传失败:', error);
      message.error('详情图上传失败');
    } finally {
      setUploading(false);
    }
  };

  // 删除图片
  const handleDeleteImage = async (index: number) => {
    try {
      await deleteProductImage(product!.id, index);
      message.success('图片删除成功');
      loadExistingImages(); // 重新加载图片
      onOk();
    } catch (error) {
      console.error('图片删除失败:', error);
      message.error('图片删除失败');
    }
  };

  // 普通图片上传配置
  const uploadProps = {
    beforeUpload: (file: File) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        message.error('图片大小不能超过5MB!');
        return false;
      }

      const normalImages = getNormalImages();
      const selectedCount = fileList.length;

      if (normalImages.length + selectedCount >= 4) {
        message.error(`当前已有${normalImages.length}张普通图片，最多只能再选择${4 - normalImages.length}张!`);
        return false;
      }

      return false; // 阻止自动上传
    },
    onChange: ({ fileList: newFileList }: any) => {
      const normalImages = getNormalImages();
      const maxAllowed = 4 - normalImages.length;
      setFileList(newFileList.slice(0, maxAllowed));
    },
    fileList,
    multiple: true,
    listType: 'picture-card' as const,
    accept: 'image/*',
  };

  // 详情图上传配置
  const detailUploadProps = {
    beforeUpload: (file: File) => {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        message.error('只能上传图片文件!');
        return false;
      }

      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        message.error('图片大小不能超过2MB!');
        return false;
      }

      return false; // 阻止自动上传
    },
    onChange: ({ fileList: newFileList }: any) => {
      setDetailFileList(newFileList.slice(-1)); // 只保留最后1个文件
    },
    fileList: detailFileList,
    multiple: false,
    listType: 'picture-card' as const,
    accept: 'image/*',
  };

  useEffect(() => {
    if (visible && product) {
      loadExistingImages();
    } else if (!visible) {
      setFileList([]);
      setDetailFileList([]);
      setExistingImages(['', '', '', '', '']);
    }
  }, [visible, product]);

  return (
    <Modal
      title={
        <div className="flex items-center">
          <PictureOutlined className="mr-2" />
          管理商品图片 - {product?.name}
        </div>
      }
      open={visible}
      onCancel={onCancel}
      width={700}
      footer={[
        <Button key="cancel" onClick={onCancel}>
          取消
        </Button>,
        <Button
          key="upload"
          type="primary"
          icon={<UploadOutlined />}
          loading={uploading}
          onClick={handleUpload}
          disabled={fileList.length === 0}
        >
          上传普通图片
        </Button>,
        <Button
          key="uploadDetail"
          type="default"
          icon={<UploadOutlined />}
          loading={uploading}
          onClick={handleDetailUpload}
          disabled={detailFileList.length === 0}
        >
          上传详情图（暂C端没有配置相应的占位，上传无法显示在C端。）
        </Button>,
      ]}
    >
      <div className="space-y-6">
        {/* 现有普通图片展示 */}
        <div>
          <div className="flex justify-between items-center mb-3">
            <h4 className="font-medium">商品图片 ({getNormalImages().length}/4)：</h4>
            <Tag color={getNormalImages().length >= 4 ? 'red' : 'blue'}>
              {getNormalImages().length >= 4 ? '已满' : `还可上传${4 - getNormalImages().length}张`}
            </Tag>
          </div>

          <div className="grid grid-cols-4 gap-3">
            {[0, 1, 2, 3].map((index) => {
              const imageUrl = existingImages[index];
              return (
                <div key={index} className="relative group border border-dashed rounded h-24 flex items-center justify-center">
                  {imageUrl ? (
                    <>
                      <img
                        src={imageUrl}
                        alt={`商品图片${index + 1}`}
                        className="w-full h-full object-cover rounded border"
                      />
                      <div className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity">
                        <Popconfirm
                          title="确认删除这张图片吗？"
                          onConfirm={() => handleDeleteImage(index)}
                          okText="确认"
                          cancelText="取消"
                        >
                          <Button
                            type="primary"
                            danger
                            size="small"
                            icon={<CloseOutlined />}
                            className="w-6 h-6 flex items-center justify-center p-0"
                          />
                        </Popconfirm>
                      </div>
                      <div className="absolute bottom-1 left-1 bg-black bg-opacity-50 text-white text-xs px-1 rounded">
                        {index + 1}
                      </div>
                    </>
                  ) : (
                    <div className="text-gray-400 text-xs text-center">
                      位置 {index + 1}<br />暂无图片
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </div>

        {/* 现有详情图展示 */}
        <div>
          <h4 className="font-medium mb-3">详情图（位置5）：</h4>
          <div className="relative group inline-block border border-dashed rounded w-32 h-32 flex items-center justify-center">
            {getDetailImage() ? (
              <>
                <img
                  src={getDetailImage()}
                  alt="商品详情图"
                  className="w-full h-full object-cover rounded border"
                />
                <div className="absolute top-1 right-1 opacity-0 group-hover:opacity-100 transition-opacity">
                  <Popconfirm
                    title="确认删除详情图吗？"
                    onConfirm={() => handleDeleteImage(4)} // 删除位置4的图片
                    okText="确认"
                    cancelText="取消"
                  >
                    <Button
                      type="primary"
                      danger
                      size="small"
                      icon={<CloseOutlined />}
                      className="w-6 h-6 flex items-center justify-center p-0"
                    />
                  </Popconfirm>
                </div>
                <div className="absolute bottom-1 left-1 bg-black bg-opacity-50 text-white text-xs px-1 rounded">
                  详情
                </div>
              </>
            ) : (
              <div className="text-gray-400 text-xs text-center">
                暂无详情图
              </div>
            )}
          </div>
        </div>

        {/* 上传普通图片区域 */}
        {getNormalImages().length < 4 && (
          <div>
            <h4 className="font-medium mb-2">上传商品图片：</h4>
            <div className="mb-2 text-sm text-gray-600">
              • 支持 JPG、PNG、GIF、WebP 格式
              • 单个文件不超过 2MB
              • 还可上传 {4 - getNormalImages().length} 张图片
            </div>
            <Upload.Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <PictureOutlined />
              </p>
              <p className="ant-upload-text">点击或拖拽文件到此区域上传</p>
              <p className="ant-upload-hint">
                还可上传 {4 - getNormalImages().length} 张商品图片
              </p>
            </Upload.Dragger>
          </div>
        )}

        {/* 上传详情图区域 */}
        <div>
          <h4 className="font-medium mb-2">上传详情图：</h4>
          <div className="mb-2 text-sm text-gray-600">
            • 详情图用于商品详情页展示
            • 支持 JPG、PNG、GIF、WebP 格式
            • 单个文件不超过 2MB
          </div>
          <Upload.Dragger {...detailUploadProps}>
            <p className="ant-upload-drag-icon">
              <PictureOutlined />
            </p>
            <p className="ant-upload-text">点击或拖拽详情图到此区域</p>
            <p className="ant-upload-hint">
              {getDetailImage() ? '重新上传详情图' : '上传商品详情图'}
            </p>
          </Upload.Dragger>
        </div>
      </div>
    </Modal>
  );
};

// 产品特性管理模态框组件
const ProductFeaturesModal: React.FC<{
  visible: boolean;
  product: Product | null;
  features: ProductFeature[];
  loading: boolean;
  onCancel: () => void;
  onOk: () => void;
  onFeaturesChange: (features: ProductFeature[]) => void;
}> = ({ visible, product, features, loading, onCancel, onOk, onFeaturesChange }) => {
  const [form] = Form.useForm();
  const [addModalVisible, setAddModalVisible] = useState(false);

  // 添加新特性 - 本地操作，保存时统一提交
  const handleAddFeature = (values: CreateFeatureRequest) => {
    const newFeature: ProductFeature = {
      id: features.length > 0 ? Math.max(...features.map(f => f.id)) + 1 : 1,
      title: values.title,
      description: values.description || '',
      icon: values.icon || 'star',
      highlight: values.highlight || false,
      order: features.length + 1
    };
    
    const updatedFeatures = [...features, newFeature];
    onFeaturesChange(updatedFeatures);
    setAddModalVisible(false);
    form.resetFields();
    message.success('添加特性成功，请点击"保存配置"提交到服务器');
  };

  // 删除特性 - 本地操作，保存时统一提交
  const handleDeleteFeature = (featureId: number) => {
    const updatedFeatures = features.filter(f => f.id !== featureId);
    // 重新排序
    const reorderedFeatures = updatedFeatures.map((feature, index) => ({
      ...feature,
      order: index + 1
    }));
    onFeaturesChange(reorderedFeatures);
    message.success('删除特性成功，请点击"保存配置"提交到服务器');
  };

  // 更新特性顺序
  const moveFeature = (dragIndex: number, hoverIndex: number) => {
    const newFeatures = [...features];
    const dragFeature = newFeatures[dragIndex];
    newFeatures.splice(dragIndex, 1);
    newFeatures.splice(hoverIndex, 0, dragFeature);
    onFeaturesChange(newFeatures);
  };

  // 保存特性配置 - 转换为字符串数组发送给后端
  const handleSave = async () => {
    if (!product) return;
    
    try {
      // 将对象数组转换为字符串数组
      const featureStrings = features.map(feature => feature.title);
      
      // 使用特性更新API，发送字符串数组
      const response = await updateProductFeatures(product.id, featureStrings as any);
      
      if (response.success) {
        message.success('保存特性配置成功');
        onOk();
      } else {
        message.error(response.message || '保存特性配置失败');
      }
    } catch (error) {
      console.error('保存特性配置失败:', error);
      message.error('保存特性配置失败');
    }
  };

  // 重置为默认配置
  const handleReset = async () => {
    if (!product) return;
    
    try {
      const response = await resetProductFeatures(product.id);
      if (response.success) {
        message.success('重置特性配置成功');
        
        // 适配返回的数据格式
        const features = response.data.features || [];
        let processedFeatures: ProductFeature[] = [];
        
        if (Array.isArray(features) && features.length > 0) {
          if (typeof features[0] === 'string') {
            // 字符串数组格式，转换为对象数组
            const stringFeatures = features as unknown as string[];
            processedFeatures = stringFeatures.map((title: string, index: number) => ({
              id: index + 1,
              title: title,
              description: '',
              icon: 'star',
              highlight: false,
              order: index + 1
            }));
          } else {
            // 已经是对象数组格式
            processedFeatures = features as ProductFeature[];
          }
        }
        
        onFeaturesChange(processedFeatures);
      } else {
        message.error(response.message || '重置特性配置失败');
      }
    } catch (error) {
      console.error('重置特性配置失败:', error);
      message.error('重置特性配置失败');
    }
  };

  const iconOptions = [
    { label: '⭐ 星星', value: 'star' },
    { label: '🚀 火箭', value: 'rocket' },
    { label: '⚡ 闪电', value: 'lightning' },
    { label: '🎯 目标', value: 'target' },
    { label: '💎 钻石', value: 'diamond' },
    { label: '🔥 火焰', value: 'fire' },
    { label: '💪 力量', value: 'power' },
    { label: '🛡️ 盾牌', value: 'shield' },
  ];

  return (
    <>
      <Modal
        title={`管理产品特性 - ${product?.name}`}
        open={visible}
        onCancel={onCancel}
        onOk={handleSave}
        width={800}
        maskClosable={false}
        footer={[
          <Button key="reset" onClick={handleReset} icon={<ResetOutlined />}>
            重置为默认
          </Button>,
          <Button key="cancel" onClick={onCancel}>
            取消
          </Button>,
          <Button key="save" type="primary" onClick={handleSave}>
            保存配置
          </Button>,
        ]}
      >
        <div className="space-y-4">
          <div className="flex justify-between items-center">
            <h4 className="font-medium">产品核心特性</h4>
            <Button 
              type="primary" 
              icon={<PlusOutlined />}
              onClick={() => setAddModalVisible(true)}
            >
              添加特性
            </Button>
          </div>

          {loading ? (
            <div className="text-center py-8">
              <span className="text-gray-500">正在加载特性...</span>
            </div>
          ) : (
            <List
              dataSource={features}
              locale={{ emptyText: '暂无特性，点击上方按钮添加' }}
              renderItem={(feature, index) => (
                <List.Item
                  key={feature.id}
                  actions={[
                    <Tooltip title="上移">
                      <Button
                        type="link"
                        size="small"
                        icon={<UpOutlined />}
                        disabled={index === 0}
                        onClick={() => moveFeature(index, index - 1)}
                      />
                    </Tooltip>,
                    <Tooltip title="下移">
                      <Button
                        type="link"
                        size="small"
                        icon={<DownOutlined />}
                        disabled={index === features.length - 1}
                        onClick={() => moveFeature(index, index + 1)}
                      />
                    </Tooltip>,
                    <Popconfirm
                      title="确认删除"
                      description={`确定要删除特性 "${feature.title}" 吗？`}
                      onConfirm={() => handleDeleteFeature(feature.id)}
                      okText="确认"
                      cancelText="取消"
                    >
                      <Button
                        type="link"
                        size="small"
                        danger
                        icon={<DeleteOutlined />}
                      />
                    </Popconfirm>
                  ]}
                >
                  <List.Item.Meta
                    avatar={
                      <div className="text-2xl">
                        {iconOptions.find(opt => opt.value === feature.icon)?.label?.split(' ')[0] || '⭐'}
                      </div>
                    }
                    title={
                      <div className="flex items-center space-x-2">
                        <span className="font-medium">{feature.title}</span>
                        {feature.highlight && (
                          <Tag color="gold" icon={<StarFilled />}>
                            重点特性
                          </Tag>
                        )}
                        <Tag color="blue">#{feature.order}</Tag>
                      </div>
                    }
                    description={feature.description || '暂无描述'}
                  />
                </List.Item>
              )}
            />
          )}
        </div>
      </Modal>

      {/* 添加特性模态框 */}
      <Modal
        title="添加产品特性"
        open={addModalVisible}
        onCancel={() => {
          setAddModalVisible(false);
          form.resetFields();
        }}
        onOk={() => form.submit()}
        maskClosable={false}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAddFeature}
        >
          <Form.Item
            name="title"
            label="特性标题"
            rules={[{ required: true, message: '请输入特性标题' }]}
          >
            <Input placeholder="请输入特性标题" />
          </Form.Item>

          <Form.Item
            name="description"
            label="特性描述"
          >
            <Input.TextArea placeholder="请输入特性描述" rows={3} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="icon"
                label="特性图标"
                initialValue="star"
              >
                <Select placeholder="请选择图标">
                  {iconOptions.map(option => (
                    <Select.Option key={option.value} value={option.value}>
                      {option.label}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="highlight"
                label="重点特性"
                valuePropName="checked"
              >
                <Switch checkedChildren="是" unCheckedChildren="否" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </>
  );
};

const ProductList: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [modalVisible, setModalVisible] = useState(false);
  const [configModalVisible, setConfigModalVisible] = useState(false);
  const [imagesModalVisible, setImagesModalVisible] = useState(false);
  const [featuresModalVisible, setFeaturesModalVisible] = useState(false);
  const [editingProduct, setEditingProduct] = useState<Product | null>(null);
  const [selectedProduct, setSelectedProduct] = useState<Product | null>(null);
  const [currentFeatures, setCurrentFeatures] = useState<ProductFeature[]>([]);
  const [featuresLoading, setFeaturesLoading] = useState(false);
  const [categories, setCategories] = useState<Category[]>([]);
  const [categoriesLoading, setCategoriesLoading] = useState(false);
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();

  // 获取类别数据
  const fetchCategories = async () => {
    try {
      setCategoriesLoading(true);
      const response = await getCategoryTree(true); // 只获取活跃的类别
      if (response.data.success) {
        setCategories(response.data.data);
      }
    } catch (error) {
      console.error('获取类别失败:', error);
    } finally {
      setCategoriesLoading(false);
    }
  };

  // 将树形类别数据转换为平铺的选项数据
  const flattenCategories = (categories: Category[], level = 0): { value: number; label: string; }[] => {
    let result: { value: number; label: string; }[] = [];

    categories.forEach(category => {
      const prefix = '　'.repeat(level); // 使用全角空格缩进
      result.push({
        value: category.id,
        label: `${prefix}${category.name}`
      });

      if (category.children && category.children.length > 0) {
        result = result.concat(flattenCategories(category.children, level + 1));
      }
    });

    return result;
  };


  const getCategoryTitle = (category: string) => {
    switch (category) {
      case 'gaming':
        return '游戏本';
      case 'office':
        return '办公本';
      case 'workstation':
        return '工作站';

      default:
        return '其他';
    }

  }

  // 根据category_id查找类别名称
  const getCategoryName = (categoryId?: number): string => {
    if (!categoryId) return '未分类';

    const findCategory = (cats: Category[]): Category | null => {
      for (const cat of cats) {
        if (cat.id === categoryId) return cat;
        if (cat.children) {
          const found = findCategory(cat.children);
          if (found) return found;
        }
      }
      return null;
    };

    const category = findCategory(categories);
    return category?.name || '未知类别';
  };

  // 表格列配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '商品名称',
      dataIndex: 'name',
      key: 'name',
      width: 200,
    },
    {
      title: 'SKU',
      dataIndex: 'sku',
      key: 'sku',
      width: 120,
    },
    {
      title: '品牌',
      dataIndex: 'brand',
      key: 'brand',
      width: 100,
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      render: (category: string) => getCategoryTitle(category),
    },
    {
      title: '类别',
      dataIndex: 'category_id',
      key: 'category_id',
      width: 120,
      render: (categoryId: number) => getCategoryName(categoryId),
    },

    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 100,
      render: (price: any) => {
        const numPrice = typeof price === 'number' ? price : parseFloat(price) || 0;
        return `¥${numPrice.toFixed(2)}`;
      },
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock',
      width: 80,
      render: (stock: number) => (
        <Tag color={stock > 10 ? 'green' : stock > 0 ? 'orange' : 'red'}>
          {stock}
        </Tag>
      ),
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      width: 80,
      render: (rating: any, record: Product) => {
        const numRating = typeof rating === 'number' ? rating : parseFloat(rating) || 0;
        return (
          <div>
            <div>{numRating.toFixed(1)}⭐</div>
            <div style={{ fontSize: '12px', color: '#666' }}>({record.review_count})</div>
          </div>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusMap = {
          active: { color: 'green', text: '有效' },
          inactive: { color: 'orange', text: '无效' },
          discontinued: { color: 'red', text: '已下架' },
        };
        const config = statusMap[status as keyof typeof statusMap] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '标记',
      key: 'flags',
      width: 120,
      render: (record: Product) => (
        <Space>
          {record.isFeatured && <Tag color="blue">特色</Tag>}
          {record.isHot && <Tag color="red">热门</Tag>}
        </Space>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      width: 180,
      render: (date: string) => new Date(date).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 300,
      render: (record: Product) => (
        <Space wrap>
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => handleView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<SettingOutlined />}
            onClick={() => handleConfig(record)}
          >
            规格
          </Button>
          <Button
            type="link"
            size="small"
            icon={<PictureOutlined />}
            onClick={() => handleImages(record)}
          >
            图片
          </Button>
          <Button
            type="link"
            size="small"
            icon={<StarOutlined />}
            onClick={() => handleFeatures(record)}
          >
            特性
          </Button>
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  // 获取产品列表
  const fetchData = async (page: number = currentPage, size: number = pageSize) => {
    try {
      setLoading(true);
      const searchValues = searchForm.getFieldsValue();

      const params: ProductQueryParams = {
        page,
        limit: size,
        ...searchValues,
      };

      const response = await getProductList(params);

      if (response.success) {
        setProducts(response.data.items || []);
        setTotal(response.data.pagination.total);
        setCurrentPage(page);
        setPageSize(size);
      } else {
        message.error(response.message || '获取产品列表失败');
      }
    } catch (error) {
      console.error('获取产品列表失败:', error);
      message.error('获取产品列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 事件处理
  const handleSearch = () => {
    fetchData(1, pageSize);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchData(1, pageSize);
  };

  const handleTableChange = (pagination: any) => {
    fetchData(pagination.current, pagination.pageSize);
  };

  const handleAdd = () => {
    setEditingProduct(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record: Product) => {
    setEditingProduct(record);
    form.setFieldsValue({
      ...record,
      category_id: record.category_id,
      isFeatured: record.isFeatured,
      isHot: record.isHot,
    });
    setModalVisible(true);
  };

  const handleView = (record: Product) => {
    Modal.info({
      title: `产品详情: ${record.name}`,
      content: (
        <div>
          <p><strong>SKU:</strong> {record.sku}</p>
          <p><strong>品牌:</strong> {record.brand}</p>
          <p><strong>类别:</strong> {getCategoryName(record.category_id)}</p>
          <p><strong>价格:</strong> ¥{(typeof record.price === 'number' ? record.price : parseFloat(record.price) || 0).toFixed(2)}</p>
          <p><strong>库存:</strong> {record.stock}</p>
          <p><strong>销量:</strong> {record.sales}</p>
          <p><strong>评分:</strong> {typeof record.rating === 'number' ? record.rating : parseFloat(record.rating) || 0} ({record.review_count}条评价)</p>
          <p><strong>状态:</strong> {record.status}</p>
          {record.description && <p><strong>描述:</strong> {record.description}</p>}
        </div>
      ),
      width: 600,
    });
  };

  const handleDelete = (record: Product) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除商品 "${record.name}" 吗？`,
      onOk: async () => {
        try {
          await deleteProduct(record.id);
          message.success('删除成功');
          fetchData();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleConfig = (record: Product) => {
    setSelectedProduct(record);
    setConfigModalVisible(true);
  };

  const handleImages = (record: Product) => {
    setSelectedProduct(record);
    setImagesModalVisible(true);
  };

  const handleFeatures = async (record: Product) => {
    setSelectedProduct(record);
    setFeaturesLoading(true);
    setFeaturesModalVisible(true);
    
    try {
      const response = await getProductFeatures(record.id);
      if (response.success) {
        console.log('特性数据:', response.data.features);
        
        // 适配字符串数组格式，转换为对象数组
        const features = response.data.features || [];
        let processedFeatures: ProductFeature[] = [];
        
        if (Array.isArray(features) && features.length > 0) {
          if (typeof features[0] === 'string') {
            // 字符串数组格式，转换为对象数组
            const stringFeatures = features as unknown as string[];
            processedFeatures = stringFeatures.map((title: string, index: number) => ({
              id: index + 1,
              title: title,
              description: '',
              icon: 'star',
              highlight: false,
              order: index + 1
            }));
          } else {
            // 已经是对象数组格式
            processedFeatures = features as ProductFeature[];
          }
        }
        
        setCurrentFeatures(processedFeatures);
      } else {
        message.error(response.message || '获取产品特性失败');
      }
    } catch (error) {
      console.error('获取产品特性失败:', error);
      message.error('获取产品特性失败');
    } finally {
      setFeaturesLoading(false);
    }
  };

  const handleConfigOk = async (productId: number, configData: any, isEdit: boolean) => {
    try {
      // configData 现在包含了表单数据和components
      const requestData: CreateConfigRequest = {
        name: configData.name,
        description: configData.description,
        category: configData.category,
        total_price: configData.total_price,
        performance_score: configData.performance_score,
        image_url: configData.image_url || '',
        components: configData.components
      };

      if (isEdit) {
        // 先查找现有配置的ID
        const response = await getConfigList({ keyword: selectedProduct?.name, limit: 1 });
        if (response.success && response.data.items && response.data.items.length > 0) {
          const existingConfig = response.data.items[0];
          await updateConfig(existingConfig.id, requestData);
          message.success('规格更新成功');
        } else {
          // 如果找不到现有配置，创建新的
          await createConfig(requestData);
          message.success('规格创建成功');
        }
      } else {
        // 创建新配置
        await createConfig(requestData);
        message.success('规格添加成功');
      }

      setConfigModalVisible(false);
      // 刷新产品列表
      fetchData();
    } catch (error) {
      console.error(`${isEdit ? '更新' : '添加'}产品规格失败:`, error);
      message.error(`${isEdit ? '更新' : '添加'}产品规格失败`);
    }
  };

  const handleModalOk = async () => {
    try {
      const values = await form.validateFields();

      const productData: CreateProductRequest | UpdateProductRequest = {
        ...values,
        isFeatured: values.isFeatured || false,
        isHot: values.isHot || false,
      };

      if (editingProduct) {
        await updateProduct(editingProduct.id, productData);
        message.success('更新成功');
      } else {
        await createProduct(productData as CreateProductRequest);
        message.success('创建成功');
      }

      setModalVisible(false);
      fetchData();
    } catch (error) {
      console.error('保存失败:', error);
      message.error('保存失败');
    }
  };

  useEffect(() => {
    fetchData();
    fetchCategories();
  }, []);

  // 搜索字段配置
  const searchFields: SearchFieldConfig[] = [
    {
      name: 'keyword',
      type: 'input',
      placeholder: '商品名称/SKU/品牌',
      width: 200,
      prefix: <SearchOutlined />
    },
    {
      name: 'category_id',
      type: 'select',
      placeholder: '选择类别',
      width: 150,
      options: flattenCategories(categories).map(option => ({
        label: option.label,
        value: option.value
      }))
    },
    {
      name: 'status',
      type: 'select',
      placeholder: '选择状态',
      width: 120,
      options: [
        { label: '有效', value: 'active' },
        { label: '无效', value: 'inactive' },
        { label: '已下架', value: 'discontinued' }
      ]
    }
  ];

  // 工具栏操作配置
  const toolbarActions: ToolbarAction[] = [
    {
      key: 'create',
      label: '添加产品',
      type: 'primary',
      icon: <PlusOutlined />,
      onClick: handleAdd
    }
  ];

  // 分页配置
  const paginationConfig: PaginationConfig = {
    current: currentPage,
    pageSize: pageSize,
    total: total,
    showTotal: (total: number) => `共 ${total} 条记录`,
    showSizeChanger: true,
    showQuickJumper: true,
    onChange: handleTableChange,
  };

  return (
    <div className="space-y-6">
      {/* 搜索区域 */}
      <SearchForm
        fields={searchFields}
        form={searchForm}
        onSearch={handleSearch}
        onReset={handleReset}
        loading={loading}
      />

      {/* 产品列表 */}
      <DataTable<Product>
        title="产品列表"
        columns={columns}
        dataSource={products}
        rowKey="id"
        loading={loading}
        pagination={paginationConfig}
        toolbarActions={toolbarActions}
        scroll={{ x: 1400 }}
      />

      <Modal
        title={editingProduct ? '编辑产品' : '添加产品'}
        open={modalVisible}
        onOk={handleModalOk}
        onCancel={() => setModalVisible(false)}
        width={600}
        maskClosable={false}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="name"
            label="商品名称"
            rules={[{ required: true, message: '请输入商品名称' }]}
          >
            <Input placeholder="请输入商品名称" />
          </Form.Item>

          <Form.Item
            name="sku"
            label="SKU"
            rules={[{ required: true, message: '请输入SKU' }]}
          >
            <Input placeholder="请输入SKU" />
          </Form.Item>

          <Form.Item
            name="brand"
            label="品牌"
            rules={[{ required: true, message: '请输入品牌' }]}
          >
            <Input placeholder="请输入品牌" />
          </Form.Item>

          <Form.Item
            name="category_id"
            label="类别"
            rules={[{ required: true, message: '请选择类别' }]}
          >
            <Select
              placeholder="请选择类别"
              loading={categoriesLoading}
              showSearch
              filterOption={(input, option) =>
                String(option?.label ?? '').toLowerCase().includes(input.toLowerCase())
              }
            >
              {flattenCategories(categories).map(option => (
                <Option key={option.value} value={option.value} label={option.label}>
                  {option.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="price"
                label="价格"
                rules={[{ required: true, message: '请输入价格' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入价格"
                  min={0}
                  precision={2}
                  formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                  parser={value => value!.replace(/¥\s?|(,*)/g, '') as any}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="stock"
                label="库存"
                rules={[{ required: true, message: '请输入库存' }]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="请输入库存"
                  min={0}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="status"
            label="状态"
            rules={[{ required: true, message: '请选择状态' }]}
          >
            <Select placeholder="请选择状态">
              <Option value="active">有效</Option>
              <Option value="inactive">无效</Option>
              <Option value="discontinued">已下架</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入商品描述" rows={3} />
          </Form.Item>

          <Row gutter={16}>
            <Col span={12}>
              <Form.Item name="isFeatured" label="特色商品" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="isHot" label="热门商品" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>

      <ProductConfigModal
        visible={configModalVisible}
        product={selectedProduct}
        onCancel={() => setConfigModalVisible(false)}
        onOk={handleConfigOk}
      />

      <ProductImagesModal
        visible={imagesModalVisible}
        product={selectedProduct}
        onCancel={() => setImagesModalVisible(false)}
        onOk={() => {
          setImagesModalVisible(false);
          fetchData(); // 刷新产品列表
        }}
      />

      <ProductFeaturesModal
        visible={featuresModalVisible}
        product={selectedProduct}
        features={currentFeatures}
        loading={featuresLoading}
        onCancel={() => setFeaturesModalVisible(false)}
        onOk={() => {
          setFeaturesModalVisible(false);
          fetchData(); // 刷新产品列表
        }}
        onFeaturesChange={setCurrentFeatures}
      />
    </div>
  );
};

export default ProductList; 